<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use App\Services\Common;
use App\Services\UploadFiles;
use App\Services\RSACrypt;
use DB;
header("Access-Control-Allow-Origin: *");
/**
 * Class Controller
 * @package App\Http\Controllers
 */
class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests, Common;

    private $redis;
    const DOMAIN = '//192.168.2.125:5000/';
    const IMG_SIZE = 1024 * 1024;
    const OneDay = 60 * 60 * 24;
    /**
     * Controller constructor.
     */
    public function __construct()
    {
        //$this->middleware('app');
        $this->redis = Redis::connection('default');
    }

    /**
     * 添加Redis缓存
     * @param $key
     * @param $value
     * @param int $timeout
     */
    protected function setRedisCache($key, $value, $timeout = 0)
    {
        $res = $this->redis->set($key, json_encode($value));

        if ($timeout > 0) {
            $res = $this->redis->expire($key, $timeout);
        }
        return $res;
    }

    /**
     * 获取Redis缓存
     * @param $key
     * @return mixed
     */
    protected function getRedisCache($key)
    {
        $value = $this->redis->get($key);
        return json_decode($value);
    }

    /**
     * 删除Redis缓存
     * @param $key
     * @return mixed
     */
    protected function delRedisCache($key)
    {
        return $this->redis->del($key);
    }

    /**
     * 清空所有Redis缓存
     * @return mixed
     */
    protected function flushAllRedisCache()
    {
        return $this->redis->flushall();
    }
    /**
     * 生成RSA公钥和私钥
     */
    function RSAGenerate()
    {
//        $rsa = new RSACrypt('./rsaKey');
//        var_dump($rsa);
    }

    /**
     * 对图片进行检测并添加域名
     * @param $img
     * @return string
     */
    protected function imageAddPrefix($img)
    {
        if (!empty($img) && is_string($img) && stripos($img, 'http') === false) {
            $img = self::DOMAIN . $img;
        }
        return $img;
    }

    /**
     * 对图片进行检测并去除域名
     * @param $img
     * @return string
     */
    protected function imageRemovePrefix($img)
    {
        return strstr($img, 'upload');
    }

    /**
     * @param Request $request
     * @return string
     */
    function uploadFile(Request $request)
    {
        //判断请求中是否包含name=file的上传文件
        if (!$request->hasFile('file')) {
            return $this->returnJson($this->warningCode, '上传文件不能为空');
        }
        $file = $request->file('file');
        //判断文件上传过程中是否出错
        if (!$file->isValid()) {
            return $this->returnJson($this->warningCode, '文件上传出错');
        }

        $path = date('Y') . '/' . date('m') . '/' . date('d');

        $upload = new UploadFiles($file);

        $upload->setMaxSize(self::IMG_SIZE)//文件上传大小限制
        ->setAllowExt(['png', 'jpeg', 'jpg'])//文件后缀名限制
        ->setAllowMine(['image/png', 'image/jpeg', 'image/jpg'])//文件类型限制
        ->setImageFlag(true); //检测是否是有效图片

        $img_path = $upload->uploadFile('upload/' . $path);

        if (empty($res)) return $this->returnJson($this->warningCode, '文件保存失败');

        return $this->returnJson($this->successCode, '文件上传成功', compact('img_path'));

    }

    /**
     * @param Request $request
     * @return string
     */
    function uploadBase64(Request $request)
    {
        $base64 = $this->validateParam('上传文件', $request->base64, '', 0, true);

        $size = self::IMG_SIZE;

        if (strlen($base64) > $size) {
            return $this->returnJson($this->warningCode, '上传文件过大，文件大小不要超过' . ($size / 1024) . 'kb');
        }

        $path = date('Y') . '/' . date('m') . '/' . date('d');

        $upload = new UploadFiles($base64);

        $res = $upload->uploadBase64('upload/' . $path);

        if (empty($res[0])) return $this->returnJson($this->warningCode, '文件上传失败', $res[1]);

        $img_path = $this->imageAddPrefix($res[1]);

        return $this->returnJson($this->successCode, '文件上传成功', compact('img_path'));
    }

    /**
     * 获取Redis缓存，没有就查询数据库
     * @param $key
     * @param $func
     * @param int $timeout
     * @return mixed
     */
    protected function getCache($key, $func, $timeout = 0)
    {
        $data = $this->getRedisCache($key);

        if (empty($data)) {
            $data = $func();
            $this->setRedisCache($key, $data, $timeout);
        }

        return $data;
    }

    /**
     * 阿里大于发送短信
     * @param string $sign_name 短信签名
     * @param $param    短信参数变量
     * @param $mobile   发送方手机号
     * @param $template 短信模板
     * @return mixed|\ResultSet|\SimpleXMLElement
     */
    /*function sendMsg($sign_name = '', $param, $mobile, $template)
    {
        require_once (app_path() . '/Tools/aliDayu/TopSdk.php');

        $c = new \TopClient;
        $c->appkey = $this->appkey;
        $c->secretKey = $this->secretKey;
        $req = new \AlibabaAliqinFcSmsNumSendRequest;
        $req->setExtend('extend');
        $req->setSmsType("normal");
        $req->setSmsFreeSignName($sign_name);
        $req->setSmsParam($param);
        $req->setRecNum($mobile);
        $req->setSmsTemplateCode($template);
        $resp = $c->execute($req);
        return $resp;
    }*/

}
